package com.sky.task;


import com.sky.entity.Orders;
import com.sky.entity.Shop;
import com.sky.orders.service.OrderService;
import com.sky.shop.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 订单管理  定时任务
 */
@Slf4j
@Component
public class OrderTask {


    //订单未支付超时时间
    private static final Long ORDER_TIMEOUT = 15L;

    //店铺打烊状态
    private static final Integer SHOP_BUSINESS_STATUS = 0;
    //店铺名称
    private static final String SHOP_NAME = "苍穹外卖";
    //派送中订单 2h 自动检查判定为已送达
    private static final Integer ORDER_DELIVERY_TIME = 2;



    @Resource
    private OrderService orderService;

    @Resource
    private ShopService shopService;


    /**
     * 定时任务 处理下单未支付超时15分钟的订单
     */
    public void processTimeOutOrder(){

        // 1.查询订单状态status=1待支付、payStatus=0未支付、下单时间+15min < 当前时间 的订单集合
        // SQL: select * from orders where status = 1 and pay_status = 0 and (select date_add(order_time), interval 15 minute) < now()
        List<Orders> ordersList = orderService.getTimeOutOrders(Orders.PENDING_PAYMENT, Orders.UN_PAID, ORDER_TIMEOUT);
        log.info("下单超时未支付订单有: {}条需处理--", ordersList.size());

        // 2.判断集合是否为空  为空不处理
        if( !CollectionUtils.isEmpty(ordersList) ){
            //AtomicInteger统计
            AtomicInteger count = new AtomicInteger(0);
            for (Orders orders : ordersList) {
                Orders updateOrder = Orders.builder()
                        .id(orders.getId())              //订单id
                        .status(Orders.CANCELLED)        //订单状态改为6 取消
                        .cancelReason("订单超时，自动取消")  //取消原因
                        .cancelTime(LocalDateTime.now()) //取消时间
                        .build();
                orderService.updateById(updateOrder);
                count.incrementAndGet();
            }
            log.info("下单超时未支付订单，已处理: {}条--", count.get());
        }
    }




    /**
     * 定时任务
     *        店铺打烊后，处理一直处于配送中的订单
     */
    public void processDeliveryOrder(){

        // 1.查询本店铺是否是打烊状态
        Shop shop = shopService.getShopByNameAndStatus(SHOP_NAME, SHOP_BUSINESS_STATUS);
        log.info("当前店铺营业状态: {}" , (Objects.isNull(shop) || shop.getShopStatus() == 1) ? "营业" : "打烊");

        // 2.打烊状态，则查询订单表状态为派送中的订单
        if(Objects.nonNull(shop) && shop.getShopStatus() == SHOP_BUSINESS_STATUS){
            //店铺已打烊了，查询订单状态status=4派送中、下单时间+2h < 当前时间 的订单集合
            List<Orders> ordersList = orderService.getDeliveryOrders(Orders.DELIVERY_IN_PROGRESS, ORDER_DELIVERY_TIME);
            log.info("订单派送时间超过2h的有: {}条需处理--", ordersList.size());

            // 3.判断集合是否为空  为空不处理
            if( !CollectionUtils.isEmpty(ordersList) ){
                //AtomicInteger统计
                AtomicInteger count = new AtomicInteger(0);
                for (Orders orders : ordersList) {
                    Orders updateOrder = Orders.builder()
                            .id(orders.getId())       //订单id
                            .status(Orders.COMPLETED) //订单状态改为5 配送完成
                            .build();
                    orderService.updateById(updateOrder);
                    count.incrementAndGet();
                }
                log.info("订单派送时间超过2h的已处理: {}条--", count.get());
            }
        }
    }










}
